<?php
/**
 * 通用方法文件
 *
 */
date_default_timezone_set('Asia/Shanghai');
session_start();
global $config, $pagenow;
$config = require('config.php');
define('BASIC_PATH', str_replace('\\', '/', dirname(dirname(__FILE__))) . '/');

$pagenow = isset($_GET['p']) ? strtolower(stripslashes($_GET['p'])) : '';

//是否登录
function is_logged($jump = false) {
    global $pagenow;
    if (isset($_SESSION['wbox_is_login']) && $_SESSION['wbox_is_login']) {
        if ($jump && $pagenow == 'login') {
            header('Location: index.php');
            die();
        }
        return true;
    }

    if ($jump && $pagenow != 'login' && $pagenow != 'f') {
        header('Location: index.php?p=login');
        die();
    }
    return false;
}

function C($name, $echo = false) {
    global $config;
    if (!isset($config[$name])) {
        return;
    }

    if (!$echo) {
        return $config[$name];
    }

    echo $config[$name];
}

function uploader($sid_info) {

    include('uploader.class.php');

    $upload = new Upload(array(
        'mimes' => C('file_mimes'), //允许上传的文件MiMe类型
        'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
        'exts' => C('file_types'), //允许上传的文件后缀
        'autoSub' => false, //自动子目录保存文件
        'subName' => array('date', 'Y-m-d'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
        'rootPath' => BASIC_PATH, //保存根路径
        'savePath' => './Uploads/', //保存路径
        'saveName' => array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
        'saveExt' => 'f', //文件保存后缀，空则使用原后缀
        'replace' => false, //存在同名是否覆盖
    ));

    $info = $upload->upload();

    if ($info) {

        foreach ($info as $k => $v) {
            unset($info[$k]['md5']);
            unset($info[$k]['sha1']);
            unset($info[$k]['sha1']);
            unset($info[$k]['key']);
        }
        $sid_info['files'] = $info;
        $sid_info['time'] = time();
        if (wb_set_json($sid_info)) {
            return_json(['count' => count($info), 'sid' => $sid_info['sid'], 'password' => $sid_info['password'], 'exp' => ($sid_info['exp'] > 0) ? $sid_info['exp'] . ' 小时' : '永久有效']);
        }
        return_json('写入记录文件出错', 400);
    } else {
        return_json($upload->getError(), 400);
    }
}

//读取token
function wb_get_json($sid) {
    $string = @file_get_contents(BASIC_PATH . "Jsons/wbox_{$sid}_sid.php");
    return json_decode(trim(str_replace('<?php die(); /* 这里是为了防止恶意读取 */ ?>', '', $string)), true);
}

//设置token
function wb_set_json($info) {
    return file_put_contents(BASIC_PATH . "Jsons/wbox_{$info['sid']}_sid.php", '<?php die(); /* 这里是为了防止恶意读取 */ ?>' . json_encode($info, true));
}

/**
 * 返回json
 * @param $data
 * @param int $code
 */
function return_json($data, $code = 200) {
    header('Content-Type:application/json');
    exit(json_encode([
        'code' => $code,
        'msg' => $code == 200 ? 'success' : $data,
        'data' => $code != 200 ? '' : $data
    ]));
}

/**
 * 创建一个唯一的SID，并将获取到的 post 参数存入$_SESSION
 */
function create_sid($post = false) {
    $chars = 'abcdefghijklmnopqrstuvwxyz1235689';
    $chars = '1235689';
    mt_srand(10000000 * (double)microtime());
    do {
        for ($i = 0, $sid = '', $len = strlen($chars) - 1; $i < 6; $i++) {
            $sid .= $chars[mt_rand(0, $len)];
        }
        $bool = file_exists(BASIC_PATH . '/Jsons/wbox_' . $sid . '_sid.php');
    } while ($bool);

    $post = $post ?: $_POST;

    if ($post['type'] == 2) {
        $post['sid'] = $sid;
        $post['files'] = [];
        $post['time'] = time();
        $post['wordtext'] = htmlspecialchars($post['wordtext'], ENT_QUOTES);
        if (wb_set_json($post)) {
            return_json(['count' => 0, 'sid' => $sid, 'password' => $post['password'], 'exp' => ($post['exp'] > 0) ? $post['exp'] . ' 小时' : '永久有效']);
        }
    }
    unset($post['wordtext']);
    $_SESSION['upload_tmp'] = array_merge($post, ['sid' => $sid]);
    return_json($sid);
}

/**
 * 获取所有文件
 * @param int $max
 * @return array
 */
function get_all_jsons($max = 20) {
    $jsons = [];
    //这里预留个如果系统开启了免登陆这里就获取session内存的sid
    $i = 0;
    foreach (glob(BASIC_PATH . "Jsons/wbox_*_sid.php") as $json_file) {
        $i++;
        if ($i > $max) {
            break;
        }
        $string = @file_get_contents($json_file);
        $jsons[] = json_decode(trim(str_replace('<?php die(); /* 这里是为了防止恶意读取 */ ?>', '', $string)), true);
    }

    //根据时间排序一下由新到久
    $tmp = [];
    foreach ($jsons as $k => $v) {
        $tmp[$k] = $v['time'];
    }
    array_multisort($tmp, SORT_DESC, SORT_NUMERIC, $jsons);

    return $jsons;
}

/**
 * 检查文件是否到期，或超过下载次数
 */
function check_files() {
    $all_files = get_all_jsons(100);
    $count = 0;
    $json_count = 0;
    $now_time = time();
    foreach ($all_files as $json) {
        //检查是否到期
        if ($json['exp'] > 0 && ($now_time - $json['time']) > ($json['exp'] * 60 * 60)) {
            if ($json['type'] == 1) {
                foreach ($json['files'] as $file) {
                    $file_path = BASIC_PATH . $file['savepath'] . $file['savename'];
                    if (file_exists($file_path)) {
                        //删除文件
                        unlink($file_path);
                        $count++;
                    }
                }
            }

            //删除json文件
            unlink(BASIC_PATH . "Jsons/wbox_{$json['sid']}_sid.php");
            $json_count++;
        }
    }

    return_json(['all_file' => count($all_files), 'del_file' => $count, 'del_json' => $json_count]);
}


/**
 * 返回系统url
 * @param bool $current 是否返回当前页面完整url否则返回程序url
 * @return string
 */
function get_bash_url($current = true) {
    $pageURL = 'http';
    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";

    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"];
    }
    if ($current) {
        $pageURL .= $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= '/' . str_replace($_SERVER['DOCUMENT_ROOT'], '', BASIC_PATH);
    }

    return $pageURL;
}